package cn.tedu._05weibo.comment.exception;

import cn.tedu._05weibo.comment.response.JsonResult;
import cn.tedu._05weibo.comment.response.StatusCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;

//设置全局异常处理器
//@ControllerAdvice
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandlen {
    @ExceptionHandler
    public JsonResult doHandleIllegalAccessException(IllegalAccessException ex) {
        String message = ex.getMessage();
        log.error("IllegalAccessException:" + message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);//操作失败
    }

    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException ex) {
        String message = ex.getMessage();
        log.error("RuntimeException:" + message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);//操作失败
    }

    @ExceptionHandler
    public JsonResult doHandleException(Exception ex) {
        String message = ex.getMessage();
        log.error("Exception:" + message);
        return new JsonResult(StatusCode.OPERATION_FAILED, message);//操作失败
    }

    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        String message = ex.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR, message);//操作失败
    }
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException ex) {
        String message = ex.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + message);
        return new JsonResult(StatusCode.VALIDATED_ERROR);//操作失败
    }

    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable ex) {
        String message = ex.getMessage();
        log.error("Throwable:" + message);
        return new JsonResult(StatusCode.THROWABLE_ERROR, message);//操作失败
    }

}
